package cn.com.zonesion.rfiddemo.fragment.aboutfragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.com.zonesion.rfiddemo.R;
import cn.com.zonesion.rfiddemo.base.BaseFragment;
import cn.com.zonesion.rfiddemo.update.UpdateService;

@SuppressLint("ValidFragment")
public class AboutFragment extends BaseFragment{
    /**
     * 用来展示二维码
     */
    @BindView(R.id.qr_download_app)
    ImageView qrDownloadApp;
    /**
     * 当前版本
     */
    @BindView(R.id.tv_current_version)
    TextView tvCurrentVersion;
    /**
     * 最新版本
     */
    @BindView(R.id.tv_latest_version)
    TextView tvLatestVersion;

    private String verName;
    private String v;

    /**
     * Unbinder对象，用来解除ButterKnife与Fragment对象的绑定
     */
    private Unbinder unbinder;
    private int screenWidth;
    private int screenHeight;

    @SuppressLint("ValidFragment")
    public AboutFragment(String verName,String v) {
        this.verName = verName;
        this.v = v;
    }

    @Override
    public View initView() {
        //获取屏幕的宽高，单位是像素
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
        View view = View.inflate(mContext, R.layout.about_item, null);
        unbinder = ButterKnife.bind(this,view);
        return view;
    }

    @Override
    public void initData() {
        super.initData();
        init();
    }



    private void init(){
        tvCurrentVersion.setText(verName);
        tvLatestVersion.setText(v);
        //传入字符串，动态生成相应的二维码图片

        String url = "http://zhiyun360.com/custom/FwsPlatform/SmartWatering.apk";
        Bitmap qrBitmap = generateBitmap(url,screenWidth/2 ,screenHeight/2 );
        //给二维码图片中间添加相应的logo
        Bitmap finalBitmap = addLogo(qrBitmap, BitmapFactory.decodeResource(getResources(), R.drawable.downloadicon));
        //将二维码显示在ImageView控件上
        qrDownloadApp.setImageBitmap(finalBitmap);
    }
    /**
     * 该方法用来生成相应的二维码图片，并以Bitmap的形式返回
     * @param content 指定的要生成的二维码的内容的字符串形式
     * @param width 生成的二维码的宽度，单位为像素
     * @param height 生成的二维码的高度，单位为像素
     * @return 生成的二维码的Bitmap对象
     */
    private Bitmap generateBitmap(String content, int width, int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 给二维码图片添加中心logo
     * @param qrBitmap 生成的二维码图片的Bitmap对象
     * @param logoBitmap 要添加的LOGO的图片的Bitmap对象
     * @return 一个添加了LOGO的二维码图片的Bitmap对象
     */
    private Bitmap addLogo(Bitmap qrBitmap, Bitmap logoBitmap) {
        int qrBitmapWidth = qrBitmap.getWidth();
        int qrBitmapHeight = qrBitmap.getHeight();
        int logoBitmapWidth = logoBitmap.getWidth();
        int logoBitmapHeight = logoBitmap.getHeight();
        Bitmap blankBitmap = Bitmap.createBitmap(qrBitmapWidth, qrBitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(blankBitmap);
        canvas.drawBitmap(qrBitmap, 0, 0, null);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        float scaleSize = 1.0f;
        while ((logoBitmapWidth / scaleSize) > (qrBitmapWidth / 5) || (logoBitmapHeight / scaleSize) > (qrBitmapHeight / 5)) {
            scaleSize *= 2;
        }
        float sx = 1.0f / scaleSize;
        canvas.scale(sx, sx, qrBitmapWidth / 2, qrBitmapHeight / 2);
        canvas.drawBitmap(logoBitmap, (qrBitmapWidth - logoBitmapWidth) / 2, (qrBitmapHeight - logoBitmapHeight) / 2, null);
        canvas.restore();
        return blankBitmap;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //解除ButterKnife与HistoricalFragment的绑定
        unbinder.unbind();
    }
    @OnClick({R.id.btn_to_update})
    public void onclick(View view){
        switch (view.getId()) {
            case  R.id.btn_to_update:
                new updateApkTask().execute("");
                break;


        }
    }
    private class updateApkTask extends AsyncTask<String,String,String> {
        String url_version = "http://zhiyun360.com/custom/droid/apk/ZCloudTools.txt";
        String url_apk = "http://zhiyun360.com/custom/droid/apk/ZCloudTools.apk";
        @Override
        protected String doInBackground(String... strings) {
            HttpURLConnection connection = null;
            InputStreamReader in = null;
            URL url;
            try {
                url = new URL(url_version);
                connection = (HttpURLConnection) url.openConnection();
                connection.setReadTimeout(30000);
                connection.setRequestMethod("GET");
                connection.setDoInput(true);
                connection.setRequestProperty("ContentType",
                        "text/xml;charset=utf-8");
                in = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(in);
                StringBuffer strBuffer = new StringBuffer();
                String line = null;
                while ((line = bufferedReader.readLine()) != null){
                    strBuffer.append(line);
                }
                connection.disconnect();

                String v = strBuffer.toString();
                return v;
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            //作UI线程的修改
            if(result.length() != 0 && !result.equals(verName)) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage("检测到新的版本"+result+"是否更新软件");
                builder.setTitle("软件更新");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(getActivity(), UpdateService.class);
                        i.putExtra("url", url_apk);
                        getActivity().startService(i);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        }
    }
}
